package role

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRoleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleListLogic {
	return &GetRoleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetRoleListLogic) GetRoleList(in *backend.RoleListReq) (*backend.RoleListResp, error) {
	// logrus.Info(fmt.Sprintf("RoleListReq: %+v", in))

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order string = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.SysRoleColumns.ID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.SysRoleColumns.Sort+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.SysRoleColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	filterMap := make(map[string]map[string][]any)
	if in.Ids != nil {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) > 0 {
			return &backend.RoleListResp{}, nil
		} else {
			filterMap[model.SysRoleColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
		}
	}
	if !restricted {
		page = in.Page
		pageSize = in.PageSize
	}

	statusIn := modelx.UniqueInterfaces(stati, 32)
	statusMap := make(map[string][]any)
	if len(statusIn) > 0 {
		statusMap["in"] = statusIn
	}
	if in.Status != nil {
		statusMap["equalTo"] = []any{*in.Status}
	}
	filterMap[model.SysRoleColumns.Status] = statusMap

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) > 0 {
		filterMap[model.SysRoleColumns.Name] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Name)},
		}
	}
	if in.Code != nil && len(strings.TrimSpace(*in.Code)) > 0 {
		filterMap[model.SysRoleColumns.Code] = map[string][]any{
			"equalTo": []any{strings.TrimSpace(*in.Code)},
		}
	}
	if in.Remark != nil && len(strings.TrimSpace(*in.Remark)) > 0 {
		filterMap[model.SysRoleColumns.Remark] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Remark)},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThan"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThanOrEqualTo"] = endTimeIn
	}
	filterMap[model.SysRoleColumns.CreatedAt] = createdAtMap

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	} else {
		orderBy = model.SysRoleColumns.Sort
	}

	res, count, err := l.svcCtx.SysRole.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, 1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp := &backend.RoleListResp{
		Total: uint64(count),
	}
	for _, v := range res {
		resp.List = append(resp.List, &backend.RoleInfo{
			Id:            pointy.GetPointer(v.ID),
			Name:          pointy.GetPointer(v.Name),
			Code:          pointy.GetPointer(v.Code),
			Status:        pointy.GetPointer(uint32(v.Status)),
			Sort:          pointy.GetPointer(uint32(v.Sort)),
			Remark:        pointy.GetPointer(v.Remark),
			DefaultRouter: pointy.GetPointer(v.DefaultRouter),
			CreatedAt:     pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
			UpdatedAt:     pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			DeletedAt:     pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
		})
	}

	return resp, nil
}
